# -*- coding: utf-8 -*-
# =============================================================================
#     FileName:
#         Desc: 以表格形式展示Redis的慢日志信息
#       Author: GGA
#        Email:
#     HomePage:
#      Version: 1.0.1
#   LastChange: 2020-12-20
#      History:
# =============================================================================

import datetime
import fire
import redis
from prettytable import PrettyTable


class RedisSlowLog(object):
    def __init__(self, redis_host, redis_port, redis_auth):
        self.redis_host = redis_host
        self.redis_port = redis_port
        self.redis_auth = redis_auth

    def _get_connection(self):
        return redis.StrictRedis(host=self.redis_host, port=self.redis_port, password=self.redis_auth, db=0)

    def show(self, slow_log_size=-1):
        redis_conn = self._get_connection()
        if slow_log_size < 0:
            slow_log_size = -1
        slow_logs = redis_conn.slowlog_get(num=slow_log_size)
        pt = PrettyTable()
        pt.field_names = ["id", "duration_ms", "start_time", "command"]
        pt.align["command"] = "l"
        for slow_log in slow_logs:
            pt_row = [
                slow_log["id"],
                "%0.2f" % round(slow_log["duration"] / 1000, 2),
                datetime.datetime.fromtimestamp(slow_log["start_time"]).strftime("%Y-%m-%d %H:%M:%S"),
                slow_log["command"].decode("utf8", errors="ignore")[0:100]
            ]
            pt.add_row(pt_row)
        print(pt)


def main(redis_host: str = "127.0.0.1", redis_port: int = 6379,
         redis_auth: str = "",
         slow_log_size: int = 100):
    """
    格式化显示Redis慢日志信息
    :param redis_host: Redis服务器地址
    :param redis_port: Redis服务器端口
    :param redis_auth: Redis服务器秘钥
    :param slow_log_size: 要显示的Slow Log数量
    :return: 
    """
    rsl = RedisSlowLog(redis_host=redis_host, redis_port=redis_port, redis_auth=redis_auth)
    rsl.show(slow_log_size=slow_log_size)


if __name__ == '__main__':
    fire.Fire(main)
